package com.svs.common.utils.data;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.svs.common.utils.data.entity.DBLink;

public class JdbcColumnUtil {
	
	static Logger logger = LoggerFactory.getLogger(JdbcColumnUtil.class) ;

	
	public static List<Map<String, String>> getColumns(DBLink dbLink,String tbname) {
		List<Map<String, String>> columnsList = new ArrayList<>() ;
		String dbName = dbLink.getDbName();
		try {
			Driver driver = (Driver) Class.forName(dbLink.getSourceType().getDriver()).newInstance();
			String jdbcUrl = dbLink.getSourceType().urlFormat();
			jdbcUrl = MessageFormat.format(jdbcUrl, dbLink.getHostName(), dbLink.getPort() + "", dbName);
			Properties info = new Properties();
			info.put("user", dbLink.getUsername());
			info.put("password", dbLink.getPassword());
			Connection conn = driver.connect(jdbcUrl, info);
			columnsList =  getColumns(conn,tbname);
		} catch (Exception e) {
			logger.error("get Columns error========="+e.getMessage());
		}
		return columnsList ;
	}
	
	/**
	 * 获取列信息
	 * 
	 * @param conn
	 * @param tbname
	 * @return
	 */
	public static  List<Map<String, String>> getColumns(Connection conn , String tbname) {
		List<Map<String, String>> results = new ArrayList<Map<String, String>>();
		try {
			ResultSet rs = conn.getMetaData().getColumns(null, null, tbname, (String) null);
			while (rs.next()) {
				Map<String, String> result = new HashMap<String, String>();
				String name = rs.getString("COLUMN_NAME");
				String type = rs.getString("TYPE_NAME").toUpperCase();
				String comments = rs.getString("REMARKS")+"" ;
				result.put("name", name);
				result.put("type", type);
				result.put("comments", comments);
				results.add(result);
			}
			conn.close();
		} catch (Exception e) {
			logger.error("get Columns error========="+e.getMessage());
		}
		return results ;
	}
	
}
